package seace.services;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import seace.dao.ParticipanteDao;
import seace.model.Cracha;
import seace.model.Participante;
import seace.utils.Constants;
import seace.utils.Utilidades;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.BarcodeEAN;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfWriter;

public class GerarCrachas implements Service {

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String action = request.getParameter("action");

		Participante participante = new Participante();
		ParticipanteDao dao = new ParticipanteDao();

		if (action != null) {
			if (action.equals(Constants.TODOS)) {
				List<Participante> participantes = dao.getParticipantes();
				dao.closeConection();
				getTodosCrachas(request, response, participantes);
			}
			if (action.equals(Constants.UM)) {
				try {
					Integer inscricao = Integer.parseInt(request
							.getParameter("inscricao"));
					participante.setInscricao(inscricao);

					Participante participanteBd = dao.getParticipante(participante);
					dao.closeConection();
					if (participanteBd != null)
						getCrachaParticipante(request, response, participanteBd);
					else {
						PrintWriter out = response.getWriter();
						out.print("Participante Inexistente");
					}

				} catch (Exception e) {
					PrintWriter out = response.getWriter();
					out
							.print("Não foi possível fazer consulta a base de dados!");
					e.printStackTrace();
				}

			}
		} else {
			PrintWriter out = response.getWriter();
			out.print("Inscrição Invalida!");
		}
	}

	private void getTodosCrachas(HttpServletRequest request,
			HttpServletResponse response, List<Participante> participantes)
			throws IOException {
		Cracha cracha = new Cracha();
		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		try {

			PdfWriter writer = PdfWriter.getInstance(cracha, baos);

			cracha.open();

			Image img = Image.getInstance("/var/www/images/basecracha.png");
			img.scalePercent(31);
			img.setAbsolutePosition(0, 0);

			BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
					BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);

			PdfContentByte under, over;
			under = writer.getDirectContentUnder();
			over = writer.getDirectContent();
			
			for (Iterator<Participante> iterator = participantes.iterator(); iterator
					.hasNext();) {

				Participante participante = (Participante) iterator.next();

				under.addImage(img);

				BarcodeEAN codeEAN = new BarcodeEAN();
				codeEAN.setCodeType(BarcodeEAN.EAN8);
				codeEAN.setCode(Utilidades.getCodigoEAN8(participante.getInscricao()+""));
				System.out.println(participante.getInscricao());
				codeEAN.setFont(bf);

				over.beginText();
				over.setFontAndSize(bf, 14);
				over.setTextMatrix(45, 80);

				// Limita a MAX_CHAR 20
				if (participante.getNome().length() > 30)
					participante.setNome(participante.getNome().substring(0, 30));

				over.showText(participante.getNome().toUpperCase());
				over.endText();

				Image imageEAN = codeEAN.createImageWithBarcode(over, null,null);
				imageEAN.setAbsolutePosition(135, 150);
				imageEAN.scalePercent(150);
				over.addImage(imageEAN);

				cracha.newPage();
			}

		} catch (IOException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		cracha.close();

		// setting some response headers
		response.setHeader("Expires", "0");
		response.setHeader("Cache-Control",
				"must-revalidate, post-check=0, pre-check=0");
		response.setHeader("Pragma", "public");
		// setting the content type
		response.setContentType("application/pdf");
		// the contentlength is needed for MSIE!!!
		response.setContentLength(baos.size());
		// write ByteArrayOutputStream to the ServletOutputStream
		response.setHeader("Content-Disposition",
				"attachment; filename=\"crachas.pdf\"");
		ServletOutputStream out = response.getOutputStream();
		baos.writeTo(out);
		out.flush();
	}
	
	private void getCrachaParticipante(HttpServletRequest request,
			HttpServletResponse response, Participante participante)
			throws IOException {
		Cracha cracha = new Cracha();
		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		try {

			PdfWriter writer = PdfWriter.getInstance(cracha, baos);

			cracha.addTitle("Sistema de Credenciamento");
			cracha.addAuthor("Unemat/Colider-MT");

			cracha.open();

			Image img = Image.getInstance("/var/www/images/basecracha.png");
			img.setAbsolutePosition(0, 0);

			BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
					BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);

			PdfContentByte under, over;
			under = writer.getDirectContentUnder();
			over = writer.getDirectContent();

			under.addImage(img);

			BarcodeEAN codeEAN = new BarcodeEAN();
			codeEAN.setCodeType(BarcodeEAN.EAN8);
			codeEAN.setCode(Utilidades.getCodigoEAN8(participante.getInscricao()+""));
			codeEAN.setFont(bf);

			over.beginText();
			over.setFontAndSize(bf, 14);
			over.setTextMatrix(60, 80);
			over.showText(participante.getNome());
			over.endText();

			Image imageEAN = codeEAN.createImageWithBarcode(over, null, null);
			imageEAN.setAbsolutePosition(135, 200);
			imageEAN.scalePercent(150);
			over.addImage(imageEAN);

		} catch (IOException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		cracha.close();

		// setting some response headers
		response.setHeader("Expires", "0");
		response.setHeader("Cache-Control",
				"must-revalidate, post-check=0, pre-check=0");
		response.setHeader("Pragma", "public");
		// setting the content type
		response.setContentType("application/pdf");
		// the contentlength is needed for MSIE!!!
		response.setContentLength(baos.size());
		// write ByteArrayOutputStream to the ServletOutputStream
		response.setHeader("Content-Disposition",
				"attachment; filename=\"cracha.pdf\"");
		ServletOutputStream out = response.getOutputStream();
		baos.writeTo(out);
		out.flush();
	}

}